<template>
  <div>
    <a-drawer
      v-model:visible="visible"
      class="custom-class"
      :title="title"
      placement="right"
      @close="modalClose.close"
      @after-visible-change="afterVisibleChange"
    >
      <div>
        <a-form :label-col="{ span: 8 }" :wrapper-col="{ span: 24 }" label-align="left" :layout="'vertical'">
          <a-form-item label="标识" v-bind="validateInfos.name">
            <a-input v-model:value="modelRef.name" :disabled="isEdit === 1" placeholder="输入英文标识" />
          </a-form-item>
          <a-form-item label="名称" v-bind="validateInfos.label">
            <a-input v-model:value="modelRef.label" :disabled="isDetl" placeholder="请输入名称" />
          </a-form-item>
          <a-form-item label="分类" v-bind="validateInfos.categoryIDLIST">
            <a-select
              ref="select"
              v-model:value="modelRef.categoryIDLIST"
              mode="multiple"
              @change="handleChangeCategory"
            >
              <a-select-option v-for="item in categoryList" :key="item.id" :value="item.id">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="类型" v-bind="validateInfos.type">
            <a-select ref="select" v-model:value="modelRef.type" @change="handleChangeType">
              <a-select-option v-for="item in typeList" :key="item.value" :value="item.value">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="参数定义" v-bind="validateInfos.params">
            <a-textarea
              v-model:value="modelRef.params"
              placeholder=""
              :disabled="isDetl"
              :auto-size="{ minRows: 3, maxRows: 3 }"
            />
          </a-form-item>
          <a-form-item label="上传图片">
            <filesTable v-if="isShowUpload" :images="modelRef.imageParams" @img-params="getImgParams"></filesTable>
          </a-form-item>
          <a-form-item label="html" v-bind="validateInfos.html">
            <a-textarea
              v-model:value="modelRef.html"
              placeholder="贴入代码"
              :disabled="isDetl"
              :auto-size="{ minRows: 5, maxRows: 5 }"
              @change="htmlChange"
            />
          </a-form-item>
          <a-form-item label="缩略图">
            <div id="lulantu">
              <img style="width: 100%; height: 100%" :src="smaillmap" alt="" />
            </div>
          </a-form-item>
          <a-form-item label="描述" v-bind="validateInfos.description">
            <a-textarea
              v-model:value="modelRef.description"
              placeholder="输入描述"
              :disabled="isDetl"
              :auto-size="{ minRows: 2, maxRows: 2 }"
            />
          </a-form-item>
        </a-form>
      </div>
      <div style="display: flex; justify-content: left">
        <div v-show="!isDetl">
          <a-button type="primary" @click="handleOk">{{ isDetl ? '关闭' : '确定' }}</a-button>
        </div>
        <div style="margin-left: 10px">
          <a-button @click="cancal">{{ isDetl ? '关闭' : '取消' }}</a-button>
        </div>
      </div>
      <div v-if="zt" id="lulantu3" style="width: 1920px; height: 1080px">
        <component :is="zt"></component>
      </div>
    </a-drawer>
    <a-modal v-model:visible="modalClose.modalVisible" title="关闭" @ok="modalClose.modalHandleOk">
      <span>数据未保存,确认关闭吗?</span>
    </a-modal>
  </div>
</template>
<script>
import { defineComponent, toRaw, ref, watch, defineEmits, toRefs, onMounted, reactive, nextTick } from 'vue'
import { Form } from 'ant-design-vue'
import factory from '../factory'
import html2canvas from 'html2canvas'
import regCom from '@/utils/registerComFunV2'
import filesTable from './upload'
import exp from '@/utils/regular'
const useForm = Form.useForm
export default defineComponent({
  components: { filesTable },
  props: {
    isShowEdit: { type: Boolean, default: false },
    isEdit: { type: Number, default: 0 },
    currentItemC: {
      type: Object,
      default: () => {
        return {}
      },
    },
    isDetl: { type: Boolean, default: false },
    categoryList: { type: Array, default: () => [] },
    typeList: { type: Array, default: () => [] },
  },
  emits: ['closeEdit', 'deletSuccess', 'editSuccess', 'createSuccess', 'updateSuccess'],
  setup(props, ctx) {
    const { isShowEdit, isEdit, currentItemC: currentItem, isDetl, categoryList, typeList } = toRefs(props)

    let isclickSave = false
    const htmlChange = () => {
      isclickSave = false
    }
    const modelRef = reactive({
      name: '',
      description: '',
      html: '',
      label: '',
      paramList: [],
      categoryIDLIST: [],
      type: '',
      imageParams: [],
      params: '',
    })
    const rulesRef = reactive({
      label: [
        {
          required: true,
          message: '请输入名称',
        },
        {
          pattern: exp.name.pattern,
          message: exp.name.message,
        },
        {
          max: 25,
          message: '最多输入25个字符',
        },
      ],
      name: [
        {
          required: true,
          message: '请输入英文名称',
        },
        {
          pattern: exp.key.pattern,
          message: exp.key.message,
        },
        {
          max: 20,
          message: '最多输入20个字符',
        },
      ],
      categoryIDLIST: [
        {
          required: true,
          message: '请选择分类',
        },
      ],
      type: [
        {
          required: true,
          message: '请选择类型',
        },
      ],
      description: [
        {
          max: 127,
          message: '最多输入127个字符',
        },
      ],
      paramList: [
        {
          required: false,
          message: '请输入描述',
        },
      ],
      html: [
        {
          required: true,
          message: '请贴入代码',
        },
        {
          pattern: new RegExp(/<template>([\s|\S]*)<\/template>[\s|\S]*export default([\s|\S]*)<\/script>/g),
          message: '请贴入正确的vue单文件组件代码',
        },
      ],
    })
    const { validate, validateInfos } = useForm(modelRef, rulesRef, {
      //表单验证的输出: 字段 值 提示
      onValidate: (...args) => {
        console.log('表单验证的输出: 字段 值 提示', ...args)
        if (args.length && args[0] === 'html' && args[1]) {
          if (args[1]) {
            !isclickSave && click_zhuanyuansu()
          } else {
            zt.value = null
          }
        }
      },
    })
    const onSubmit = () => {
      isclickSave = true
      validate()
        .then(() => {
          //表单验证无误后执行
          saveToAliyun()
        })
        .catch((err) => {
          console.log('error', err)
        })
    }

    //====aliyun 拿到上传图片前的签名========
    const fileList = ref(null)
    function dataURLtoFile(dataurl, filename) {
      var mime = 'image/jpg',
        bstr = atob(dataurl),
        n = bstr.length,
        u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename, { type: mime })
    }
    const saveToAliyun = () => {
      let img64 = smaillmap.value
      img64 = img64.replace('data:image/jpeg;base64,', '')
      fileList.value = dataURLtoFile(img64, 'portlet-' + modelRef.name)

      factory.getALiYunInfo().then((obj) => {
        obj.key = obj.dir + fileList.value.name
        let fd = new FormData()
        fd.append('name', fileList.value.name)
        fd.append('key', obj.key)
        fd.append('policy', obj.policy)
        fd.append('OSSAccessKeyId', obj.accessId)
        fd.append('success_action_status', '200')
        fd.append('signature', obj.signature)
        // fd.append("callback", obj.callback)
        fd.append('file', fileList.value)
        factory.uploadImg(obj.host, fd).then((res) => {
          //测试,写死resourcePath
          let img = '/test/img/p1.png' + Date.parse(new Date())
          modelRef.resourcePath = img
          modelRef.categoryId = modelRef.categoryIDLIST.join(',')
          modelRef.img = obj.key
          let imgarr = []
          modelRef.imageParams.forEach((m, n) => {
            imgarr.push({ ...m })
            if (m.url.includes('data:')) {
              delete imgarr[n].url
            }
          })
          if (isEdit.value === 0) {
            //新增
            factory.saveLayoutList({ ...modelRef, ...{ imageParams: imgarr } }).then((res) => {
              visible.value = false
              ctx.emit('createSuccess', modelRef.value)
              ctx.emit('closeEdit', false)
            })
          } else {
            //编辑
            factory.updateLayoutList({ ...modelRef, ...{ imageParams: imgarr } }).then((res) => {
              visible.value = false
              ctx.emit('updateSuccess', modelRef)
              ctx.emit('closeEdit', false)
            })
          }
        })
      })
    }

    //== 主体程序 =================================
    const visible = ref(false)
    const isShowUpload = ref(true)
    const handleOk = (e) => {
      onSubmit()
    }
    const cancal = () => {
      modalClose.close()
    }
    watch(visible, (newValue, oldValue) => {
      if (!newValue) {
        ctx.emit('closeEdit', false)
      }
    })
    const title = ref('')
    watch(isShowEdit, (newValue, oldValue) => {
      if (newValue) {
        zt.value = null
        visible.value = true
        switch (isEdit.value) {
          case 0:
            title.value = '新增'
            break
          case 1:
            title.value = '编辑'
            break
        }
        if (isDetl.value) {
          title.value = '详情'
        }
        if (title.value !== '新增') {
          let obj2 = currentItem.value
          modelRef.categoryIDLIST = obj2.categoryList.map((m) => m.id)
          factory.getDetail({ id: obj2.id }).then((res) => {
            for (let key in res.data) {
              modelRef[key] = res.data[key]
            }
            isShowUpload.value = false
            nextTick(() => {
              isShowUpload.value = true
            })
            //备份数据
            let obj = {}
            compare.forEach((key) => {
              obj[key] = modelRef[key]
            })
            modalClose.backupData = JSON.stringify(obj)
          })
        } else {
          //备份数据
          let obj = {}
          compare.forEach((key) => {
            obj[key] = modelRef[key]
          })
          modalClose.backupData = JSON.stringify(obj)
        }
      }
    })
    let compare = ['name', 'description', 'html', 'label', 'categoryIDLIST', 'type', 'params']

    //==类型选择===========================
    const handleChangeCategory = () => {
      console.log('组件管理-分类', modelRef.categoryID)
    }
    const handleChangeType = (value) => {
      console.log('组件管理-类型', value)
    }

    //===转代码转网页元素================
    const zt = ref(null)
    const click_zhuanyuansu = () => {
      zt.value = regCom(modelRef.html, modelRef.imageParams.length ? modelRef.imageParams : null)
      setTimeout(() => {
        suofang()
      }, 10)
    }
    //==缩放===========
    const smaillmap = ref(null)
    function suofang() {
      let block = document.getElementById('lulantu3')
      html2canvas(block.children[0], {
        useCORS: true,
      }).then((res) => {
        smaillmap.value = res.toDataURL('image/jpeg')
        zt.value = null
      })
    }

    //==得到 组件中的 上传的图片================
    const getImgParams = (files) => {
      modelRef.imageParams = files.map((m) => m.response)
    }

    //==确认关闭对话框======================
    const modalClose = reactive({
      backupData: '',
      close: (e) => {
        let obj = {}
        compare.forEach((key) => {
          obj[key] = modelRef[key]
        })
        if (JSON.stringify(obj) !== modalClose.backupData) {
          visible.value = true
          modalClose.modalVisible = true
          return
        }
        visible.value = false
      },
      modalVisible: false,
      modalHandleOk: () => {
        visible.value = false
      },
    })

    return {
      visible,
      handleOk,
      title,
      cancal,
      validateInfos,
      modelRef,
      zt,
      htmlChange,
      handleChangeCategory,
      handleChangeType,
      smaillmap,
      getImgParams,
      isShowUpload,
      modalClose,
    }
  },
})
</script>
<style scoped>
#lulantu {
  width: 300px;
  height: 200px;
  overflow: hidden;
  border: 1px solid #d9d9d9;
}
</style>
